import axios from 'axios';
import cookie from 'js-cookie';
import base from '../Base/Base64.js'
import login from '../api/login.js'
import router from "@/router";
import prompt from "./prompt";
// import qs from 'qs'
// import { configs } from 'eslint-plugin-prettier';

// 创建axios实例
const serve = axios.create({
    baseURL: 'http://192.168.1.188:8080/m.api',
    // baseURL: 'http://39.108.158.63:8821/m.api',
    // baseURL: 'http://192.168.1.99:8080/m.api',
    timeout: 15000
});

serve.interceptors.request.use(config => {
    // console.log(config)
    // 在发送请求之前做些什么
    config.headers['AdminToken'] = cookie.get("token")
    return config;
}, error => {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
serve.interceptors.response.use(async response => {
    if (response.data.errno!=200) {
        prompt.error(response.data.errmsg)
    }
    if (response.data.errno == 10001 || response.data.errno == 10006) {
        if (cookie.get('username') || cookie.get('password')) {  //判断账号密码是否登录
            //解密
            let account = base.decode(cookie.get('username'))
            let pass = base.decode(cookie.get('password'))
            let vseverification = cookie.get('verifica')
            let array = await login.login(
                {
                    username: account,
                    password: pass,
                    verifyCode: vseverification
                }
            )
            if (array.status == 200) {  //判断status是否成功
                var time = new Date(new Date().getTime() + 60 * 1000 *20)//过期数据
                cookie.set('token', array.data.data,{expires: time})
                return serve(response.config)
            }
        } else {
            router.push("/login")  //过期时间有过就跳转到登入页码
        }
    }
    // 对响应数据做点什么
    return response;
}, error => {
    router.push("/Home/directory")
    // 对响应错误做点什么
    return Promise.reject(error);
});
export default serve;

